package org.itboys.shop.tools;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.itboys.seller.entity.SellerMenu;

import java.util.List;
import java.util.Map;

public class SellerMenuSortUtil {
	public static List<SellerMenu> sortbyParam(List<SellerMenu> list) {
		Map<Long, List<SellerMenu>> adminmenusLists = Maps.newLinkedHashMap();

		for (SellerMenu t : list) {
			Long parentId = t.getParentId();
			List<SellerMenu> menus = adminmenusLists.get(parentId);
			if (menus == null) {
				menus = Lists.newLinkedList();
				adminmenusLists.put(parentId, menus);
			}
			menus.add(t);
		}
		List<SellerMenu> result = Lists.newLinkedList();
		addsubmenusbyId(adminmenusLists.get(0L),result,  adminmenusLists);
		return result;
	}

	private static void addsubmenusbyId(List<SellerMenu> menus,
			List<SellerMenu> resultList,
			Map<Long, List<SellerMenu>> adminmenusLists) {
		for (SellerMenu menu : menus) {
			resultList.add(menu);
			Long id = menu.getId();
			List<SellerMenu> submenus = adminmenusLists.get(id);
			if (submenus != null) {
				addsubmenusbyId( submenus,resultList, adminmenusLists);
			}
		}
	}

}
